from odoo.exceptions import UserError
from odoo import api, models


class RPBaseModelForAddress(object):
    """
    基础模型  -  Address
    该模型用于地址处理

    - id: odoo索引
    - record: odoo.model(res.partner)
    - customer_id: 客户ID(rp.customer)

    - country_id: 国家ID(res.country)
    - state_id: 省ID
    - city_id: 市ID
    - county_id: 区ID
    - street: 街道
    - postal_code_id: 邮编ID

    - first_name: 名
    - last_name: 姓
    - mobile: 电话
    - company: 公司

    - default: 默认地址 True/False
    """
    schema_json = {'type': 'object',
                   'properties': {'id': {'type': ['integer', 'null']},
                                  'first_name': {'type': ["string", "null"]},
                                  'last_name': {'type': ["string", "null"]},
                                  'mobile': {'type': ["string", "null"]},
                                  'company': {'type': ["string", "null"]},
                                  'country_id': {'type': ["integer", "null"]},
                                  'state_id': {'type': ["integer", "null"]},
                                  'city_id': {'type': ["integer", "null"]},
                                  'county_id': {'type': ["integer", "null"]},
                                  'street': {'type': ["string", "null"]},
                                  'postal_code_id': {'type': ["integer", "null"]},
                                  'default': {'type': 'boolean'}},
                   "required": ["first_name", 'last_name', 'mobile', 'country_id', 'city_id', 'postal_code_id', 'street']}

    def __init__(self, env, id=None, record=False, customer_id=None,
                 country_id=None, state_id=None, city_id=None, street='', postal_code_id=None, first_name='', last_name='', mobile='',
                 county_id=None, company='', default=False):

        self.env = env  # 传递odoo环境，非常重要

        self.id = id
        self.record = env['res.partner'].sudo().search([('id', '=', id)]) if id else record
        self.customer_id = customer_id

        self.country_id = country_id
        self.state_id = state_id
        self.city_id = city_id
        self.county_id = county_id
        self.street = street
        self.postal_code_id = postal_code_id

        self.first_name = first_name
        self.last_name = last_name
        self.mobile = mobile
        self.company = company

        self.default = default

    def search(self):
        if not any([self.id, self.record]):
            raise UserError(1001)
        self.printf()

    def unlink(self):
        if not self.record:
            raise UserError(1017)
        self.record.unlink()
        return True

    def create(self):
        if not all([self.country_id, self.state_id, self.city_id, self.street, self.postal_code_id, self.first_name, self.last_name, self.mobile]):
            raise UserError(1002)
        if not self.customer_id:
            raise UserError(1010)

        self.check_info()
        repetitive_address_rcds = self.env['res.partner'].sudo().search([('customer_address_id', '=', self.customer_id),
                                                                         ('first_name', '=', self.first_name),
                                                                         ('last_name', '=', self.last_name),
                                                                         ('mobile', '=', self.mobile),
                                                                         ('contact_company_name', '=', self.company),
                                                                         ('country_id', '=', self.country_id),
                                                                         ('state_id', '=', self.state_id),
                                                                         ('city_id', '=', self.city_id),
                                                                         ('street', '=', self.street),
                                                                         ('postal_code_id', '=', self.postal_code_id)])
        if len(repetitive_address_rcds) >= 1:
            raise UserError(1015)
        created_rcd = self.env['res.partner'].sudo().create({'rel_type': 'address',
                                                             'customer_address_id': self.customer_id,
                                                             'default_address': self.default,
                                                             'company_type': 'person',
                                                             'name': self.last_name + ' ' + self.first_name,
                                                             'first_name': self.first_name,
                                                             'last_name': self.last_name,
                                                             'mobile': self.mobile,
                                                             'contact_company_name': self.company,
                                                             'country_id': self.country_id,
                                                             'state_id': self.state_id,
                                                             'city_id': self.city_id,
                                                             'county_id': self.county_id,
                                                             'street': self.street,
                                                             'postal_code_id': self.postal_code_id})
        return created_rcd.id

    def write(self):
        if not any([self.id, self.record]):
            raise UserError(1001)
        if not self.customer_id:
            raise UserError(1010)
        if any([self.country_id, self.state_id, self.city_id, self.postal_code_id]):
            self.check_info()
            if not all([self.country_id, self.state_id, self.city_id, self.postal_code_id]):
                raise UserError(1016)
        # 查询重复
        record = self.record
        repetitive_address_rcds = self.env['res.partner'].sudo().search([('customer_address_id', '=', self.customer_id),
                                                                         ('first_name', '=', self.first_name if self.first_name else record.first_name),
                                                                         ('last_name', '=', self.last_name if self.last_name else record.last_name),
                                                                         ('mobile', '=', self.mobile if self.mobile else record.mobile),
                                                                         ('contact_company_name', '=', self.company if self.company else record.contact_company_name),
                                                                         ('country_id', '=', self.country_id if self.country_id else record.country_id.id),
                                                                         ('state_id', '=', self.state_id if self.state_id else record.state_id.id),
                                                                         ('city_id', '=', self.city_id if self.city_id else record.city_id.id),
                                                                         ('street', '=', self.street if self.street else record.street),
                                                                         ('postal_code_id', '=', self.postal_code_id if self.postal_code_id else record.postal_code_id.id)])
        if len(repetitive_address_rcds) >= 1:
            raise UserError(1015)

        self.record.write({'default_address': self.default if self.default else record.default_address,
                           'name': self.last_name + ' ' + self.first_name if any([self.last_name, self.first_name]) else record.last_name + ' ' + record.first_name,
                           'first_name': self.first_name if self.first_name else record.first_name,
                           'last_name': self.last_name if self.last_name else record.last_name,
                           'mobile': self.mobile if self.mobile else record.mobile,
                           'contact_company_name': self.company if self.company else record.contact_company_name,
                           'country_id': self.country_id if self.country_id else record.country_id.id,
                           'state_id': self.state_id if self.state_id else record.state_id.id,
                           'city_id': self.city_id if self.city_id else record.city_id.id,
                           'county_id': self.county_id if self.county_id else record.county_id.id,
                           'street': self.street if self.street else record.street,
                           'postal_code_id': self.postal_code_id if self.postal_code_id else record.postal_code_id.id})
        return self.printf()

    def check_info(self):
        # 通过邮编校验国家省市区
        postal_code_rcd = self.env['rp.postal.code'].sudo().search([('id', '=', self.postal_code_id)])
        if postal_code_rcd.country_id.id != self.country_id:
            raise UserError(1011)
            # raise invalid_business(message_code=1001)
        if postal_code_rcd.state_id.id != self.state_id:
            raise UserError(1012)
        if postal_code_rcd.city_id.id != self.city_id:
            raise UserError(1013)
        if self.county_id and postal_code_rcd.county.id != self.county_id:
            raise UserError(1014)

    def __str__(self, *args, **kwargs):
        return {'id': self.id,
                'record': self.record,
                'customer_id': self.customer_id,
                'country_id': self.country_id,
                'state_id': self.state_id,
                'city_id': self.city_id,
                'county_id': self.county_id,
                'street': self.street,
                'postal_code_id': self.postal_code_id,
                'first_name': self.first_name,
                'last_name': self.last_name,
                'mobile': self.mobile,
                'company': self.company,
                'default': self.default}

    def printf(self):
        record = self.record
        return {'id': record.id,
                'first_name': record.first_name,
                'last_name': record.last_name,
                'mobile': record.mobile,
                'company': record.contact_company_name if record.contact_company_name else '',
                'country': {'id': record.country_id.id,
                            'name': record.country_id.name},
                'state': {'id': record.state_id.id,
                          'name': record.state_id.name},
                'city': {'id': record.city_id.id,
                         'name': record.city_id.name},
                'county': {'id': record.county_id.id if record.county_id else '',
                           'name': record.county_id.name if record.county_id else ''},
                'street': record.street,
                'postal_code': {'id': record.postal_code_id.id,
                                'name': record.postal_code_id.name},
                'default': record.default_address}

